<template>
  <div>
    <van-signature @submit="signatureSubmit" />
    <!-- <van-image v-if="signatureImg" :src="signatureImg" /> -->
  </div>
</template>
<script setup>
  import { ref, watch } from 'vue'
  import { doGet, doPut, doUpload } from "@/config/http"
  import { svc } from '@/config/common'
  import { getH5UserId } from "@/config/cookie";
  import useUserStore from '@/store/modules/user'

  const emit = defineEmits(['close'])

  // 转blob对象
  const base64ToBlob = (base64Data, contentType) => {
    const sliceSize = 1024
    const byteCharacters = atob(base64Data)
    const byteArrays = []
    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {  
      const slice = byteCharacters.slice(offset, offset + sliceSize) 
      const byteNumbers = new Array(slice.length)
      for (let i = 0; i < slice.length; i++) {  
        byteNumbers[i] = slice.charCodeAt(i)
      }  
      const byteArray = new Uint8Array(byteNumbers)
      byteArrays.push(byteArray)
    }  
    const blob = new Blob(byteArrays, {type: contentType})
    return blob
  }

  // 转文件
  const base64ToFile = (base64Data, fileName, contentType = 'application/octet-stream') => {
    const blob = base64ToBlob(base64Data, contentType);
    const file = new File([blob], fileName, { type: contentType });
    return file;
  }

  // 提交
  const signatureSubmit = async (data) => {
    const fileName = '签名.png'; // 你想要的文件名
    const contentType = 'image/png'; // 文件的内容类型
    const file = base64ToFile(data.image.split(',')[1], fileName, contentType);

    let formData = new FormData();
    formData.append("file", file);
    formData.append("fileType", 'image');
    let sign = await doUpload(svc, '/customAttachment/upload', formData, false)
    let user = await doGet(svc, '/user/' + getH5UserId(), {}, false)
    user.sign = sign['id']
    await doPut(svc, '/user/modify', user, false)
    await useUserStore().getInfo()
    emit('close')
  }

</script>
<style scoped lang="scss">
</style>

